import * as signalR from '@aspnet/signalr'
import { Notification } from 'element-ui'
// 连接集线器
const connectionSignalR = new signalR.HubConnectionBuilder()
  // 请求一次后端接口,保证是可通信的状态,即状态码为101
  .withUrl('/api/chatHub', {
    skipNegotiation: true,
    transport: signalR.HttpTransportType.WebSockets
  })
  .configureLogging(signalR.LogLevel.Error) // 日志输出级别,可自行调整
  .build()

async function start() {
  try {
    await connectionSignalR.start()
    console.log('connected')
  } catch (err) {
    console.log(err)
    setTimeout(() => start(), 10000)
  }
}
// 开始接受消息
export function noticeMessage(ruleName, callback) {
  connectionSignalR.serverTimeoutInMilliseconds = 24e4
  connectionSignalR.keepAliveIntervalInMilliseconds = 12e4
  connectionSignalR.start().then(function() {
    console.log('连接成功')
  }).catch(function(ex) {
    console.log('连接失败' + ex)
    setTimeout(() => start(), 10000)
  })
  connectionSignalR.on(ruleName, function(msg) {
    var data = JSON.parse(msg)
    console.log(data)
    Notification({
      type: 'success',
      title: '消息提示',
      message: data.Content,
      position: 'bottom-right',
      onClick() {
        // 这里可以弹出展示消息列表
        // 弹出列表时候发送请求获取
      }

    })
  })
}
// 退出
export function stop() {
  connectionSignalR.stop()
}

